<template>
  <div class="page-container hide-scrollbar" ref="pageContainer">

    <div class="article-summary" v-for="summary in displayedSummaries" :key="summary.month" ref="summaryContainers"
      :style="{ marginBottom: summary.articles.length > 0 ? '4vh' : '0' }">
      <div class="month" v-if="summary.articles.length > 0">{{ formatMonthDisplay(summary.month) }}</div>
      <div class="article-item" v-for="item in summary.articles" :key="item.id" @click="getArticleDetailsData(item.id)">
        <div class="article-img" :style="{ backgroundImage: 'url(' + item.cover + ')' }"></div>
        <div class="article-text">
          <div class="article-title">{{ item.title }}</div>
          <div class="article-content">{{ item.subtitle }}</div>
        </div>
      </div>
    </div>

    <div v-if="isLoading" class="loading">加载中...</div>

    <!-- QADetail子组件 -->
    <QADetail :articleId="articleId" :isVisible="isDetailsVisible" @close="closeArticleDetails"
      @article-change="handleArticleChange" />

  </div>
</template>

<script>
import { getQAListByMonth } from '@/api/api'
import QADetail from '@/components/QADetail.vue'

export default {
  name: 'QAPage',
  components: {
    QADetail
  },
  data() {
    return {
      allSummaries: [], // 存储所有月份的数据
      displayedSummaries: [],// 显示在页面上的月份数据
      currentEarliestMonth: '',// 当前加载到的最早月份
      isLoading: false,// 是否正在加载中
      loadLock: false,// 防止重复加载的锁
      articleId: '',// 记录文章id
      isDetailsVisible: false, // 控制详情页显示/隐藏
    }
  },
  created() {
    // 初始化：获取当前月份及前两个月
    const months = this.getRecentMonths(3);
    this.currentEarliestMonth = months[months.length - 1];

    // 加载初始的3个月份数据
    months.forEach(month => {
      this.loadMonthData(month);
    });
  },
  mounted() {
    // 监听滚动事件，实现滚动加载
    this.$refs.pageContainer.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    // 移除滚动监听
    this.$refs.pageContainer.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    // 获取最近count个月份
    getRecentMonths(count) {
      const months = [];
      const today = new Date();

      for (let i = 0; i < count; i++) {
        const year = today.getFullYear();
        // 计算月份，当前月减去i
        let month = today.getMonth() + 1 - i;

        // 处理跨年情况
        if (month <= 0) {
          month += 12;
          today.setFullYear(year - 1);
        }

        // 格式化为YYYY-MM
        const monthStr = `${year}-${month.toString().padStart(2, '0')}`;
        months.push(monthStr);
      }

      return months;
    },

    // 根据传入的月份，计算并返回前一个月
    getPreviousMonth(month) {
      const [year, monthNum] = month.split('-').map(Number);
      let prevYear = year;
      let prevMonth = monthNum - 1;

      if (prevMonth < 1) {
        prevMonth = 12;
        prevYear--;
      }

      return `${prevYear}-${prevMonth.toString().padStart(2, '0')}`;
    },

    // 加载指定月份的文章数据，避免重复加载，更新显示列表
    loadMonthData(month) {
      // 检查是否已加载过该月份数据
      if (this.allSummaries.some(item => item.month === month)) {
        return;
      }

      this.isLoading = true;

      getQAListByMonth(month)
        .then(res => {
          // 存储所有月份数据
          this.allSummaries.push({
            month,
            articles: res.data
          });

          // 更新显示的数据（保持顺序）
          this.displayedSummaries = [...this.allSummaries]
            .sort((a, b) => b.month.localeCompare(a.month));
        })
        .catch(err => {
          console.error(`加载${month}数据失败:`, err);
        })
        .finally(() => {
          this.isLoading = false;
          this.loadLock = false;
        });
    },

    // 处理月份格式
    formatMonthDisplay(month) {
      const monthNum = month.split('-')[1];
      // 去除前导零
      return `${parseInt(monthNum)}月`;
    },

    // 滚动到底部时向前加载数据
    handleScroll() {
      // 如果正在加载中或已加锁，不执行
      if (this.isLoading || this.loadLock) return;

      const container = this.$refs.pageContainer;
      const lastSummary = this.$refs.summaryContainers?.[this.$refs.summaryContainers.length - 1];

      if (!lastSummary) return;

      // 计算最后一个月份容器的底部位置
      const lastSummaryBottom = lastSummary.offsetTop + lastSummary.offsetHeight;
      // 容器的滚动高度和可视高度
      const clientHeight = container.clientHeight;
      const scrollTop = container.scrollTop;

      // 当滚动到距离底部200px以内时，加载下一个月份
      if (lastSummaryBottom - scrollTop <= clientHeight + 200) {
        this.loadLock = true; // 加锁防止重复请求
        const nextMonth = this.getPreviousMonth(this.currentEarliestMonth);
        this.currentEarliestMonth = nextMonth;
        this.loadMonthData(nextMonth);
      }
    },

    // 根据文章id获取文章详情数据，显示详情页
    getArticleDetailsData(id) {
      this.articleId = id;// 记录当前文章ID
      this.isDetailsVisible = true;// 显示文章详情
    },

    // 关闭文章详情页
    closeArticleDetails() {
      this.isDetailsVisible = false;
      this.articleId = '';
    },

    // 处理子组件的文章变化事件
    handleArticleChange(newArticleId) {
      this.articleId = newArticleId;
    },



  }
}
</script>

<style scoped lang="less">
.page-container {
  padding: 10vh 10px 7vh;
  background-color: #fff;
  height: 100vh;
  overflow-y: auto;
  box-sizing: border-box;
}

.article-summary {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.month {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: #ccc;
  margin-bottom: 5px;

  &::before {
    content: '';
    width: 45%;
    height: 1px;
    transform: scaleY(0.2);
    background-color: #b9b9b9;
    margin-right: 5px;
  }

  &::after {
    content: '';
    width: 45%;
    height: 1px;
    transform: scaleY(0.2);
    background-color: #b9b9b9;
    margin-left: 5px;
  }
}

.article-item {
  height: 6vh;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 10px;
  padding: 5px 0;

  .article-img {
    height: 100%;
    border-radius: 8px;
    aspect-ratio: 1 / 1;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
  }

  .article-text {
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .article-title {
      font-size: 12px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .article-content {
      font-size: 8px;
      color: #ccc;
      padding: 5px 0;
    }
  }
}

.loading {
  text-align: center;
  padding: 15px;
  font-size: 12px;
  color: #999;
}

.hide-scrollbar {
  -ms-overflow-style: none;
  scrollbar-width: none;

  &::-webkit-scrollbar {
    display: none;
  }
}
</style>